package upload;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery.TooManyResultsException;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

@SuppressWarnings("serial")
public class UploadProfilePicture extends HttpServlet {
	
	private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		
		HttpSession session = req.getSession(true);
		String username = (String) session.getAttribute("username");
		
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
        BlobKey blobKey = blobs.get("uploadProfilePic");
        
        Key fileKey = KeyFactory.createKey("ProfilePicKey", "mediaFiles");
        try {
        	Entity file = new Entity("ProfilePic", fileKey);
        	file.setProperty("blobKey", blobKey);
        	
        	datastore.put(file);
        }
        catch (TooManyResultsException ex) {
        	Query query = new Query("ProfilePic", fileKey).addFilter("username", FilterOperator.EQUAL, username);
        	Entity pic = datastore.prepare(query).asSingleEntity();
        	BlobKey tempBlobKey = (BlobKey) pic.getProperty("blobKey");
        	blobstoreService.delete(tempBlobKey);
        	datastore.delete(pic.getKey());
        	
        	Entity file = new Entity("ProfilePic", fileKey);
        	file.setProperty("blobKey", blobKey);
        	datastore.put(file);
        }
		resp.sendRedirect("/profile.jsp");
	}
}
